package dao;
import utils.JdbcUtils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author fire'ge
 */
public class UserOperation {
    public static ResultSet checkUser(int start, int rows, Connection connection) throws SQLException {
        String sql = "select * from tb_user limit ?,?";
        //预处理mysql语句
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setInt(1, start);
        ps.setInt(2, rows);
        //获取resultSet集合
        return ps.executeQuery();
    }

    public static ResultSet checkLikeUser(String factorStr, int start, int rows, Connection connection) throws SQLException {
        //获取连接
        factorStr = "%" + factorStr + "%";
        String sql = "select * from tb_user where username like ? limit ?,?";
        //预处理mysql语句
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setNString(1, factorStr);
        ps.setInt(2, start);
        ps.setInt(3, rows);
//获得set集合，装入对象中
        return ps.executeQuery();
    }

    public static boolean addList(String name, String pwd) throws SQLException, IOException {
        Connection connection = JdbcUtils.getConnection();
        String sql = "insert into tb_user value (null,?,?,1)";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setNString(1, name);
        ps.setNString(2, pwd);
        int execute = ps.executeUpdate();
        JdbcUtils.close(null, connection, ps);
        return execute > 0;
    }

    public static ResultSet checkLogin(String username, String password, Connection connection) throws SQLException {
        //预编译sql语句
        String sql = "SELECT * FROM tb_user WHERE `username`= ? AND PASSWORD = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //插入查询语句并执行
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, password);
        //得到查询结果集
        return preparedStatement.executeQuery();
    }

    public static ResultSet checkUsername(Connection connection,String username) throws SQLException, IOException {
        String sql = "select username from tb_user where username = ?";
            //插入查询语句
            PreparedStatement preStat = connection.prepareStatement(sql);
            preStat.setString(1,username);
            //获得结果集
            return preStat.executeQuery();
    }
}